import { defineStore } from "pinia";
import { getSelect } from "@/api/user.js";
import useInstructionStore from "@/store/modules/instructionList.js";

export const useWarnPollingStore = defineStore("warnPolling", {
  state: () => ({
    POLL_INTERVAL: 120000, // 120秒轮询一次
    BATCH_SIZE: 5, // 每批处理数量
    BATCH_INTERVAL: 1000, // 批次间隔1秒
    pollTimer: null
  }),

  actions: {
    async pollingInit() {
      const instructionStore = useInstructionStore();

      // 创建请求队列
      const requestQueue = (instructionStore.list || []).map((item, index) => ({
        ...item,
        originalIndex: index
      }));

      // 分批次处理
      for (let i = 0; i < requestQueue.length; i += this.BATCH_SIZE) {
        const batch = requestQueue.slice(i, i + this.BATCH_SIZE);

        // 执行当前批次请求
        const batchPromises = batch.map(item => {
          if (item.isRead === false) {
            console.log(`跳过已读项[索引${item.originalIndex}]`);
            return null;
          }

          return getSelect({ id: item.id })
            .then(res => ({
              success: true,
              data: res,
              index: item.originalIndex
            }))
            .catch(err => ({
              success: false,
              error: err,
              index: item.originalIndex
            }));
        });

        // 过滤并执行有效请求
        const validPromises = batchPromises.filter(p => p !== null);
        const results = await Promise.allSettled(validPromises);

        // 处理结果
        results.forEach(result => {
          if (result.status === "fulfilled") {
            const { success, data, index } = result.value;
            if (success) {
              this.handleSuccessData(data, index);
            } else {
              console.error(`请求失败[索引 ${index}]:`, data.error);
            }
          } else {
            console.error("请求异常:", result.reason);
          }
        });

        // 批次间隔等待
        if (i + this.BATCH_SIZE < requestQueue.length) {
          await new Promise(resolve =>
            setTimeout(resolve, this.BATCH_INTERVAL)
          );
        }
      }
    },

    handleSuccessData(data, index) {
      const instructionStore = useInstructionStore();
      const answer = data.data?.answer;

      if (!answer) {
        console.warn(`索引 ${index}: 响应数据缺少answer字段`);
        return;
      }

      // 类型验证配置
      const validationMap = {
        2: () => answer.value !== undefined,
        3: () => answer.table?.rows?.length > 0,
        4: () => answer.option?.series?.[0]?.data?.length > 0,
        5: () => answer?.map_points?.length > 0
      };

      const isValid = validationMap[answer.type]?.();
      if (isValid) {
        instructionStore.addField(index, "answer", answer);
        console.log(`索引 ${index}: 数据存储成功`);
      } else {
        console.warn(`索引 ${index}: 类型${answer.type}数据验证失败`);
      }
    },

    startPolling() {
      const instructionStore = useInstructionStore();
      new Promise((resolve, reject) => {
        setTimeout(() => {
          if (instructionStore.list.length === 0) {
            reject("重新执行");
          } else {
            resolve("执行");
          }
        }, 1000);
      })
        .then(data => {
          if (data === "执行") {
            // 先立即执行一次
            this.pollingInit(); // 设置定时轮询
            this.pollTimer = setInterval(() => {
              this.pollingInit();
            }, this.POLL_INTERVAL);
          }
        })
        .catch(err => {
          if (err === "重新执行") {
            this.startPolling();
          }
        });
    },

    stopPolling() {
      if (this.pollTimer) {
        clearInterval(this.pollTimer);
        this.pollTimer = null;
      }
    }
  }
});
